<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <!-- @input 监听输入事件 随时变化 -->
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changeValue" />
        <!-- 树形组件 -->
        <!-- highlight-current 让选中的节点有个高亮的颜色 node-key="id" 告诉树数据中id是唯一的 @current-change="selectNode" 修改选中节点 -->
        <el-tree ref="deptTree" :data="treeData" :props="{label:'name'}" default-expand-all :expand-on-click-node="false" highlight-current node-key="id" @current-change="selectNode" />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- 点击跳转到详情页 -->
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail' )">添加员工</el-button>

          <el-button size="mini" @click="isShow = true">excel导入</el-button>

          <el-button size="mini" @click="onExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <!-- 如果用户没有头像，则取用户名第一个字为头像 -->
              <div v-else class="username">{{ row.username.charAt(0) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              <div>{{ row.formOfEmployment?'正式':'非正式' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <!-- v-xxx="'show'" -->
              <el-button v-xxx="'show'" size="mini" type="text" @click="$router.push('/employee/detail/' + row.id)">查看</el-button>
              <!-- v-xxx="'assign'" -->
              <el-button v-xxx="'assign'" size="mini" type="text" @click="onShowRoleList(row.id)">角色</el-button>

              <el-button size="mini" type="text">
                <!-- 确认删除气泡 -->
                <el-popconfirm title="确定删除该行数据吗？" @onConfirm="delEmployee(row.id)">
                  <!-- v-xxx="'del'" -->
                  <el-button slot="reference" v-xxx="'del'" style="margin-left:10px" size="mini" type="text">删除</el-button>
                </el-popconfirm>
              </el-button>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>

      </div>

    </div>
    <ImportExcel :show-excel-dialog.sync="isShow" />
    <!-- 给员工分配角色 -->
    <!-- 分配角色弹出层 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" @close="showRoleDialog = false">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <!-- el-checkbox-group必须绑定v-model绑定值收集选中的id，否则不会显示选中效果 -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}
        </el-checkbox>

      </el-checkbox-group>
      <el-row justify="center" type="flex" style="padding: 20px;">
        <el-button size="mini" type="primary" @click="onAssignRole">分配角色</el-button>
        <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
      </el-row>

    </el-dialog>

  </div>

</template>

<script>
import { getDepartmentAPI } from '@/api/department'
import { assignRolesAPI, delEmployeeAPI, exportAPI, getEmployeeDetailAPI, getEmployeeListAPI, getEnableRoleListAPI } from '@/api/employee'
import { arrayToTree } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './import-excel.vue'
// 模糊搜索字段
// 1.准备keyword变量收集数据
// 2、v-model收集数据
// 3、@input监听输入事件 随时变化
// 4、重置page为1
// 5、调用getEmployeeList重新发请求
// 6、防抖优化
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showRoleDialog: false, // 分配角色弹出层
      roleList: [], // 角色列表
      roleIds: [], // 配合v-model记录选中的id
      isShow: false,
      treeData: [],
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      total: 0,
      list: []
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentAPI()
      this.treeData = arrayToTree(res)
      this.queryParams.departmentId = this.treeData[0].id
      if (this.$refs.deptTree) {
        // 设置选中节点
        // 树组件渲染是异步的 等到更新完毕
        // $nextTick会等dom渲染完毕之后，再执行回调函数
        this.$nextTick(() => {
        // 此时意味着树渲染完毕
          this.$refs.deptTree.setCurrentKey(this.treeData[0].id)
        })
      }
      this.getEmployeeList()
    },
    selectNode(node) {
      // 修改选中节点
      this.queryParams.departmentId = node.id
      // 切换部门时讲页数重置为第一页
      this.queryParams.page = 1
      this.getEmployeeList(this.queryParams)
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListAPI(this.queryParams)
      this.total = total
      this.list = rows
    },
    // 更改页数
    changePage(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },
    changeValue() {
      // 防抖，先清除定时器
      // js是弱类型，可以不用声明timer，直接将timer挂到this对象上
      // 只要是对象，都可以动态随意分配新属性
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async delEmployee(id) {
      await delEmployeeAPI(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // excel导出
    async onExport() {
      const res = await exportAPI()
      // 响应拦截器需要判断后端给的数据类型是不是blob，特殊处理
      // 使用file-saver插件将二进制数据转为文件
      saveAs(res, '员工信息.xlsx')
    },
    async onShowRoleList(id) {
      const res = await getEnableRoleListAPI()
      const { roleIds } = await getEmployeeDetailAPI(id)
      this.showRoleDialog = true
      this.roleIds = roleIds
      this.roleList = res
      // 放data里的是响应式数据，此时的id不需要响应式，所以可以使用动态分配给this
      this.userId = id// js是弱类型，可以动态分配属性
    },
    async onAssignRole() {
      await assignRolesAPI({
        roleIds: this.roleIds,
        id: this.userId
      })
      this.showRoleDialog = false
      this.$message.success('分配角色成功')
    }
  }
}
</script>

    <style lang="scss" scoped>
    .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
  }

</style>
